package com.data.modules.wrt.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.domain.Person;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.data.common.api.CommonAPI;
import com.data.common.constant.CommonConstant;
import com.data.common.exception.Boot401Exception;
import com.data.common.exception.BootException;
import com.data.common.system.api.ISysBaseAPI;
import com.data.common.system.util.JwtUtil;
import com.data.common.system.vo.LoginUser;
import com.data.common.util.CommonUtils;
import com.data.common.util.ConvertUtils;
import com.data.modules.wrt.entity.*;
import com.data.modules.wrt.service.*;
import com.data.modules.wrt.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.data.common.constant.CommonConstant.IOT_TOKEN_START;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author boot
 */

@RestController
@RequestMapping("/wrt")
@Api(tags="wrt")
@Slf4j
@SuppressWarnings("ALL")
public class WrtController<stringWarnType> {

	@Autowired
	private IWrtDeviceService wrtDeviceService;

	@Autowired
	private IWrtCallLogService wrtCallLogService;

	@Autowired
	private IWrtAlarmLogService wrtAlarmLogService;

	@Autowired
	private IWrtOpenLogService wrtOpenLogService;

	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IWrtRoomService roomService;

	@Autowired
	private IWrtUserInfoService wrtUserInfoService;


	@ApiOperation("回调")
	@PostMapping("/v1/callBackFor")
	public Map callBackFor( @RequestParam( required = true,name ="pid") String pid,
						   @RequestParam(required = true,name ="method") String method,
						   @RequestBody(required =false) String userInfo,
						   @RequestPart(required = false,name="json") String json,
							@RequestPart(required= false,name = "captureImage") MultipartFile multipartFile,
							HttpServletRequest request) throws IOException, ServletException {
		Map map = new HashMap();
		String auth = request.getHeader("Authorization");
		if(auth.startsWith(CommonConstant.WRT_TOKEN_START)){
			auth = auth.substring(CommonConstant.WRT_TOKEN_START.length());

			if(!ObjectUtil.equals("c21hZG1pbjoxMjM0NTY=",auth)){
				map.put("code",0);
				map.put("msg","token不正确");
				return map;
			}
		}

		log.info("===pid====,{},method=,{}",pid,method);
		if(ObjectUtil.equals("device_status",method)){ //设备状态mLogin
			JSONArray jsonArray = JSONArray.fromObject(userInfo);
			List <WrtDeviceReqVo> list = JSONArray.toList(jsonArray, WrtDeviceReqVo.class);

			list.stream().forEach(x->{
				WrtDevice po = new WrtDevice();
				List<WrtDevice> list1 = wrtDeviceService.lambdaQuery().eq(WrtDevice::getSn,x.getSn()).list();
				if(ObjectUtil.isNotEmpty(list1)){
					WrtDevice vo = list1.get(0);
					vo.setLastTime(x.getLastTime());
					vo.setStatus(x.getStatus());
					wrtDeviceService.updateById(vo);

				}else{
					BeanUtils.copyProperties(x, po);
					po.setUuid(pid);
					wrtDeviceService.save(po);
				}
			});
		}

		if(ObjectUtil.equals("call_log",method)){ //对讲记录

			JSONArray jsonArray = JSONArray.fromObject(userInfo);
			List <WrtCallReqVo> list = JSONArray.toList(jsonArray, WrtCallReqVo.class);
			list.stream().forEach(x->{
				WrtCallLog po = new WrtCallLog();
				BeanUtils.copyProperties(x, po);
				po.setUuid(pid);
				wrtCallLogService.save(po);
			});
		}

		if(ObjectUtil.equals("alarm_log",method)){ //报警记录
			/**
			 * [{"targetSn":"000000000000000","unlock":0,
			 * "sourceType":0,"sourceName":"时迈科研楼一单元主门口机","sourceSn":"110010100000001","targetType":62,
			 * "targetName":"管理中心","beginTime":"2023-09-04 16:09:03","id":3,"endTime":"2023-09-04 16:09:18"}]
			 */
			JSONArray jsonArray = JSONArray.fromObject(userInfo);
			List <WrtAlarmReqVo> list = JSONArray.toList(jsonArray, WrtAlarmReqVo.class);
			list.stream().forEach(x->{
				WrtAlarmLog po = new WrtAlarmLog();
				BeanUtils.copyProperties(x, po);
				po.setUuid(pid);

				wrtAlarmLogService.addAlarmInfo(po,"smwrt");
				//wrtAlarmLogService.save(po);
			});
		}

		if(ObjectUtil.equals("unlock_log",method)) {//开门记录
			if(ObjectUtil.isNotEmpty(json)){
				JSONArray jsonArray = JSONArray.fromObject(json);
				List <WrtOpenLogReqVo> list = JSONArray.toList(jsonArray, WrtOpenLogReqVo.class);
				list.stream().forEach(x->{
					WrtOpenLog po = new WrtOpenLog();
					BeanUtils.copyProperties(x, po);
					po.setUuid(pid);
					wrtOpenLogService.save(po);
				});
			}
		}

		map.put("code",1);
		map.put("msg","成功");
		return map;
	}

	@ApiOperation("回调")
	@PostMapping("/v2/callBackFor")
	public Map callBackForv2( @RequestParam( required = false,name ="pid") String pid,
							@RequestParam(required = true,name ="method") String method,
							@RequestBody(required =false) String userInfo,
							@RequestPart(required = false,name="json") String json,
							@RequestPart(required= false,name = "captureImage") MultipartFile multipartFile,
							HttpServletRequest request) throws IOException, ServletException {
		Map map = new HashMap();

		log.info("=v2/callBackFor==pid===={},method={},json=={},userInfo==={}",pid,method,json,userInfo);
		if(ObjectUtil.equals("device_status",method)){ //设备状态mLogin
			JSONArray jsonArray = JSONArray.fromObject(userInfo);
			List<WrtDeviceReqVo> list = JSONArray.toList(jsonArray, WrtDeviceReqVo.class);

			list.stream().forEach(x->{
				WrtDevice po = new WrtDevice();
				List<WrtDevice> list1 = wrtDeviceService.lambdaQuery().eq(WrtDevice::getSn,x.getSn()).list();
				if(ObjectUtil.isNotEmpty(list1)){
					WrtDevice vo = list1.get(0);
					vo.setLastTime(x.getLastTime());
					vo.setStatus(x.getStatus());
					wrtDeviceService.updateById(vo);

				}else{
					BeanUtils.copyProperties(x, po);
					wrtDeviceService.save(po);
				}
			});
		}

		if(ObjectUtil.equals("call_log",method)){ //对讲记录

			JSONArray jsonArray = JSONArray.fromObject(userInfo);
			List <WrtCallReqVo> list = JSONArray.toList(jsonArray, WrtCallReqVo.class);
			list.stream().forEach(x->{
				WrtCallLog po = new WrtCallLog();
				BeanUtils.copyProperties(x, po);
				wrtCallLogService.save(po);
			});
		}

		if(ObjectUtil.equals("alarm_log",method)){ //报警记录

			JSONArray jsonArray = JSONArray.fromObject(userInfo);
			List<WrtAlarmReqVo> list = JSONArray.toList(jsonArray, WrtAlarmReqVo.class);
			list.stream().forEach(x->{
				WrtAlarmLog po = new WrtAlarmLog();
				BeanUtils.copyProperties(x, po);
				wrtAlarmLogService.addAlarmInfo(po,"");
			});
		}

		if(ObjectUtil.equals("unlock_log",method)) {//开门记录
			if(ObjectUtil.isNotEmpty(json)){
				JSONArray jsonArray = JSONArray.fromObject(json);
				List<WrtOpenLogReqVo> list = JSONArray.toList(jsonArray, WrtOpenLogReqVo.class);
				list.stream().forEach(x->{
					WrtOpenLog po = new WrtOpenLog();
					BeanUtils.copyProperties(x, po);
					wrtOpenLogService.save(po);
				});
			}
		}
		if(ObjectUtil.equals("send_devices",method)) {//接收设备信息
			if(ObjectUtil.isNotEmpty(userInfo)){
				//把json数据转为Java对象
				SynDevice device= JSON.parseObject(userInfo, SynDevice.class);
				if(ObjectUtil.isNotEmpty(device.getDevices_del())){
					String [] devicesIds = device.getDevices_del();
					for(String snId:devicesIds){
						QueryWrapper<WrtDevice> wrapper = new QueryWrapper<>();
						wrapper.eq("sn",snId);
						//删除设备
						wrtDeviceService.remove(wrapper);
					}
				}
			}
		}
		if(ObjectUtil.equals("send_user",method)) {//发送人员信息

			//把json数据转为Java对象
			SynUser user= JSON.parseObject(userInfo, SynUser.class);
			if(ObjectUtil.isNotEmpty(user.getPersons())){
				JSONArray jsonArray = JSONArray.fromObject(user.getPersons());

				List<WrtUserVo> list = JSONArray.toList(jsonArray, WrtUserVo.class);
				List<WrtUserInfo> userList = new ArrayList<>();
				list.stream().forEach(x->{
					WrtUserInfo po = new WrtUserInfo();
					BeanUtils.copyProperties(x, po);
					po.setUserId(x.getUserID());
					userList.add(po);

				});

				wrtUserInfoService.saveUserInfo(userList);

			}
			if(ObjectUtil.isNotEmpty(user.getPersons_del())){
				String [] userIds = user.getPersons_del();
				for(String userId:userIds){
					QueryWrapper<WrtUserInfo> wrapper = new QueryWrapper<>();
					wrapper.eq("sn",userId);
					//删除用户
					wrtUserInfoService.remove(wrapper);
				}
			}
		}

		if(ObjectUtil.equals("send_rooms",method)) {// 获取房间信息
			if(ObjectUtil.isNotEmpty(userInfo)){

				//把json数据转为Java对象
				DeleteRoom room= JSON.parseObject(userInfo, DeleteRoom.class);
				if(ObjectUtil.isNotEmpty(room.getRooms())){
					JSONArray jsonArray = JSONArray.fromObject(room.getRooms());
					List <WrtRoomVo> list = JSONArray.toList(jsonArray, WrtRoomVo.class);
					List<WrtRoom> roomList = new ArrayList<>();
					list.stream().forEach(x->{
						WrtRoom po = new WrtRoom();
						BeanUtils.copyProperties(x, po);
						roomList.add(po);

					});
					roomService.saveRoomInfo(roomList);
				}

				if(ObjectUtil.isNotEmpty(room.getRooms_del())){
					String [] roomIds = room.getRooms_del();
					for(String roomId:roomIds){
						QueryWrapper<WrtRoom> wrapper = new QueryWrapper<>();
						wrapper.eq("sn",roomId);
						//删除房间号
						roomService.remove(wrapper);
					}
				}
			}
		}

		map.put("code",1);
		map.put("msg","成功");
		return map;
	}

	@ApiOperation("测试用户信息")
	@PostMapping(value = "/wrtLogin")
	public Map wrtLogin(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		String auth = request.getHeader("Authorization");
		if(auth.startsWith(CommonConstant.WRT_TOKEN_START)){
			auth = auth.substring(CommonConstant.WRT_TOKEN_START.length());

			if(ObjectUtil.equals("c21hZG1pbjoxMjM0NTY=",auth)){
				map.put("access_token", auth);
				map.put("msg","成功");
			}else{
				map.put("msg","用户密码不正确");
			}
		}
		return map;
	}

}
